package com.itheima.web.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 替换httpservlet 根据请求的最后一段路径来进行方法转发
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //1获取请求路径
        StringBuffer requestURL = req.getRequestURL(); //brand-case/brand/selectAll
        //2获取最后一段路径,方法名
        int index= requestURL.lastIndexOf("/");
        String methodName = requestURL.substring(index+1);//

        //执行方法
        //获取 brandserlevlet字节码对象
        Class<? extends BaseServlet> aClass = this.getClass();

        //获取方法method对象
        try {
            Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }
}
